<?php

// @formatter:off
/**
 * @file register.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: register.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/services/users/register.php $
 */
// @formatter:on

global $wcPaths;

require_once __DIR__."/tools.php";

class WCServiceUsersRegister extends WCService {
	//
	// Class methods.
	public function __construct() {
		parent::__construct();

		$this->_readOnlyConflict = true;

		$this->_requiredParams["params"][] = "email";
		$this->_requiredParams["params"][] = "username";
		$this->_requiredParams["params"][] = "password";

		$this->_requiredPermissions["to"][] = WC_PERM_USER_REGISTER;
	}
	//
	// Protected methods.
	protected function load() {
		$out = false;

		if(parent::load()) {
			$this->email = isset($this->email) ? strtolower(trim($this->email)) : false;
			$this->username = isset($this->username) ? strtolower(trim($this->username)) : false;
			$this->password = isset($this->password) ? trim($this->password) : false;

			$out = true;
		}

		return $out;
	}
	protected function runPOST() {
		global $wcUsersHolder;

		$euser = $wcUsersHolder->userByEmail($this->email);
		$uuser = $wcUsersHolder->itemByName($this->username);
		/** @todo ver si esto es un array. */
		if($euser) {
			$this->setError(WC_HTTPERROR_BAD_REQUEST, "E-mail '{$this->email}' is been used by another user");
		} elseif($uuser) {
			$this->setError(WC_HTTPERROR_BAD_REQUEST, "Username '{$this->username}' is not available");
		} else {
			$user = $wcUsersHolder->create($this->username);
			if($user) {
				global $wcAction;
				global $wcThemeAssigns;
				global $wcTheme;

				$user->setPassword($this->password);
				$user->data()->email = $this->email;

				define("__EMAIL__", true);
				$wcAction = WC_EACTION_REGISTER;
				$wcThemeAssigns["TITLE"] = "Sign Up Request";
				$wcThemeAssigns["HASH"] = $user->hash_register;
				$wcThemeAssigns["USERID"] = $user->id;
				$wcThemeAssigns["USERNAME"] = $user->name();

				startTheme();

				$parser = $wcTheme->parser();
				$parser->massiveAssign($wcThemeAssigns);
				$parser->noWarnings();
				$parser->noSummary();

				if(!SendEmail($this->_email, "Sign Up Request", $parser->parse())) {
					$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "Unable to send e-mail to '{$this->_email}'");
				} else {
					$this->_count++;
				}
			} else {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "Unable to create user '{$this->_username}'");
			}
		}
	}
}
